<template>
  <div class="container">
    <!-- 左侧锚点导航 -->
    <div class="anchor-nav">
      <ul>
        <li
          v-for="item in anchorList"
          :key="item.id"
          :class="{ active: activeId === item.id }"
          @click="scrollTo(item.id)"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content" ref="content">
      <el-collapse v-model="activeNames" @change="onCollapseChange">
        <el-collapse-item
          v-for="item in anchorList"
          :id="item.id"
          :key="item.id"
          :title="item.label"
          :name="item.id"
        >
          <div class="content-block">
            <h3>{{ item.label }}</h3>
            <p>这是 {{ item.label }} 的详细内容。</p>
            <div style="height: 300px">（模拟内容高度 300px）</div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      anchorList: [
        { id: "item1", label: "简介" },
        { id: "item2", label: "内容" },
        { id: "item3", label: "示例" },
        { id: "item4", label: "附录" },
      ],
      activeId: "",
      activeNames: [],
      observer: null,
      scrolling: false,
      scrollTimer: null,
    };
  },
  mounted() {
    this.activeNames = this.anchorList.map((item) => item.id); // 展开所有
    this.$nextTick(() => {
      this.createObserver();
    });
  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect();
    }
  },
  methods: {
    scrollTo(id) {
      this.activeId = id; // 手动立即高亮
      this.scrolling = true;
      clearTimeout(this.scrollTimer);

      const el = document.getElementById(id);
      const container = this.$refs.content;
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      console.log("====================================");
      console.log(scrollTop);
      console.log("====================================");
      if (el && container) {
        const elTop = el.offsetTop;
        console.log(el.offsetTop);
        const maxScroll = container.scrollHeight - container.clientHeight;
        const targetTop = Math.min(elTop - 91, maxScroll);
        console.log("=======targetTop=============================");
        console.log(targetTop);
        console.log("===========targetTop=========================");
        container.scrollTo({
          top: targetTop,
          behavior: "smooth",
        });
        // container.scrollTop = targetTop;
        this.scrollTimer = setTimeout(() => {
          this.scrolling = false;
        }, 500); // 动画完成后解锁
      }
    },
    onCollapseChange() {
      if (this.observer) {
        this.observer.disconnect(); // 清除旧的观察
      }
      this.$nextTick(() => {
        this.createObserver(); // 重新观察
      });
    },
    createObserver() {
      const container = this.$refs.content;
      const options = {
        root: container,
        threshold: 0.5, // 更适合较小内容块
      };

      this.observer = new IntersectionObserver(this.handleIntersect, options);

      this.anchorList.forEach((item) => {
        const el = document.getElementById(item.id);
        if (el) {
          this.observer.observe(el);
        }
      });
    },
    handleIntersect(entries) {
      if (this.scrolling) return; // 跳转过程中不干扰高亮

      const visible = entries
        .filter((entry) => entry.isIntersecting)
        .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);

      if (visible.length > 0) {
        this.activeId = visible[0].target.id;
      } else {
        const container = this.$refs.content;
        if (
          container.scrollTop + container.clientHeight >=
          container.scrollHeight - 5
        ) {
          this.activeId = this.anchorList[this.anchorList.length - 1].id;
        }
      }
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.anchor-nav {
  width: 200px;
  border-right: 1px solid #ddd;
  padding: 10px;
  overflow-y: auto;
  background: #fafafa;
}

.anchor-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.anchor-nav li {
  padding: 10px;
  cursor: pointer;
  transition: background 0.3s;
}

.anchor-nav li.active {
  background-color: #409eff;
  color: white;
  font-weight: bold;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
}

.content-block {
  padding: 20px;
  margin-bottom: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>